<?php
/**
 * Description:
 * Author: hezhizheng
 * Date: 2018/7/16
 * Time: 8:46
 * Created by Created by Panxsoft.
 */

namespace App\Http\Controllers\Admin\Store\Product;

use App\Http\Controllers\ApiController;
use App\Models\Customer\Customer;
use App\Models\Store\Store;
use App\Services\Utils\Guard;
use App\Services\Youzan\ProductRepository;
use App\Services\Youzan\ProductService;

class YouzanProductController extends ApiController
{

    const ROUTE = [
        'sync_on_sale_product' => 'admin.store.sync_on_sale_product',
        'sync_inventory_product' => 'admin.store.sync_inventory_product'
    ];

    protected $productRepository;
    protected $productService;

    public function __construct(ProductRepository $productRepository, ProductService $productService)
    {
        $this->productRepository = $productRepository;
        $this->productService = $productService;
    }

    /**
     * 同步有赞再售商品
     *
     * @return array|\Illuminate\Http\Response
     * @throws \Exception
     * @throws \Throwable
     */
    public function syncItemsOnSale()
    {
        /** @var Store $store */
        $store = Guard::store();

        /** @var Customer $customer */
        $customer = $store->customer;

        $youzanAuthorizer = $store->youzanAuthorizer;
        $this->checkIsTrue($youzanAuthorizer,trans('admin.no_auth_to_youzan'));

        $items_params = $this->productRepository->assembleItemsParams();

        $list = $this->productRepository->getAllItemsOnSale($youzanAuthorizer,$items_params);

        $transformItems = $this->productService->transformItems($list, $customer, $store);

        $insert = $this->productRepository->syncProducts($transformItems, $list);

        return $this->response(compact('insert'));
    }

    /**
     * 同步有赞仓库商品
     *
     * @return array|\Illuminate\Http\Response
     * @throws \Exception
     * @throws \Throwable
     */
    public function syncItemsInventory()
    {
        /** @var Store $store */
        $store = Guard::store();
        /** @var Customer $customer */
        $customer = $store->customer;

        $youzanAuthorizer = $store->youzanAuthorizer;
        $this->checkIsTrue($youzanAuthorizer,trans('admin.no_auth_to_youzan'));

        $items_params = $this->productRepository->assembleItemsParams();

        $list = $this->productRepository->getAllItemsInventory($youzanAuthorizer,$items_params);

        $transformItems = $this->productService->transformItems($list, $customer, $store);

        $insert = $this->productRepository->syncProducts($transformItems, $list);

        return $this->response(compact('insert'));
    }
}